//
//  XXTGHomeWebViewController.m
//  XiuXiuTuanGou
//
//  Created by 王克博 on 2018/7/26.
//  Copyright © 2018年 XiuXiuTuanGou. All rights reserved.
//

#import "XXTGHomeWebViewController.h"
#import <WebKit/WebKit.h>

#import <JavaScriptCore/JavaScriptCore.h>
#import "XXTGHomeWebObject.h"

@interface XXTGHomeWebViewController ()


@end

@implementation XXTGHomeWebViewController

- (void)dealloc
{
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJSUseAppMethod_Share object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJSUseAppMethod_SaveImage object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJSUseAppMethod_Statistics object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //重新让webView加载url
    [self reloadSubViews];
    
    if ([kUserDefaults valueForKey:kUserCurrentSid]) {
        NSHTTPCookie * cookie1 = [self setCookieWithKey:kWebViewCookieSidKey value:[kUserDefaults valueForKey:kUserCurrentSid]];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie1];
    }else if ([kUserDefaults valueForKey:kUserSid]) {
        NSArray * sidArray = [kUserDefaults valueForKey:kUserSid];
        if (sidArray && sidArray.count > 0) {
            NSString * sid = [sidArray firstObject];
            NSHTTPCookie * cookie1 = [self setCookieWithKey:kWebViewCookieSidKey value:sid];
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie1];
        }
    }
    
    if ([kUserDefaults objectForKey:kUserCookie]) {
        NSHTTPCookie * cookie2 = [self setCookieWithKey:kWebViewCookieKey value:[kUserDefaults objectForKey:kUserCookie]];
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie2];
    }
    
    //约定的事件通过通知的方式传递到该页面
    //分享
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(shareEvent:) name:kJSUseAppMethod_Share object:nil];
    //保存图片到相册
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(saveImageByBase64Event:) name:kJSUseAppMethod_SaveImage object:nil];
    //收到统计事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statisticsEventNotification:) name:kJSUseAppMethod_Statistics object:nil];
}

- (void)needReloadData
{
    [self reloadSubViews];
//    [self.mainWebView reload];
}

- (void)reloadSubViews
{
    NSURL * url = [NSURL URLWithString:self.urlString];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];
    NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
    NSDictionary *headers = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    [request setHTTPShouldHandleCookies:YES];
    [request setAllHTTPHeaderFields:headers];
    [self.mainWebView loadRequest:request];
    
   // self.mainWebView.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight-XXTG_NavBarHeight-XXTG_SafeAreaBottomHeight);
    
    //js调用app方法，需要的写法
    JSContext * context = [self.mainWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    XXTGHomeWebObject * object = [XXTGHomeWebObject new];
    //创建中转对象，赋值给js的对象
    context[@"jsUseAppMethod"] = object;
}

- (NSHTTPCookie *)setCookieWithKey:(NSString *)key value:(NSString *)value
{
    NSMutableDictionary *cookieProperties = [NSMutableDictionary dictionary];
    [cookieProperties setObject:key forKey:NSHTTPCookieName];
    [cookieProperties setObject:value forKey:NSHTTPCookieValue];
    [cookieProperties setObject:@"www.ourdaidai.com" forKey:NSHTTPCookieDomain];
    [cookieProperties setObject:@"/" forKey:NSHTTPCookiePath];
//    [cookieProperties setObject:[[NSDate date] dateByAddingTimeInterval:2629743] forKey:NSHTTPCookieExpires];
    NSHTTPCookie * cookieuser = [NSHTTPCookie cookieWithProperties:cookieProperties];
    return cookieuser;
}

//MARK: - 通知事件
- (void)shareEvent:(NSNotification *)notification
{
    NSDictionary * dict = [notification userInfo];
    if (dict) {
        NSString * title = @"";
        NSString * description = @"";
        NSString * image = @"";
        NSString * url = @"";
        if (dict[@"title"]) {
            title = dict[@"title"];
        }
        if (dict[@"description"]) {
            description = dict[@"description"];
        }
        if (dict[@"image"]) {
            image = dict[@"image"];
        }
        if (dict[@"url"]) {
            url = dict[@"url"];
        }
        [self shareWithTitle:title Description:description Image:image URL:url];
    }
}

//MARK: - Event  与html约定 被调用的方法
- (void)shareWithTitle:(NSString *)title Description:(NSString *)description Image:(NSString *)image URL:(NSString *)url
{
//    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
//    NSString * timeString = [NSString stringWithFormat:@"%ld",(long)time];
//    NSString * newURL = [NSString stringWithFormat:@"%@&openKey=%@@@%@",url,_inviteShopOpenKey,timeString];
}

//保存图片到本地相册通知
- (void)saveImageByBase64Event:(NSNotification *)notification
{
    NSDictionary * userinfo = [notification userInfo];
    if (userinfo[@"imageBase64String"]) {
        NSString * imageString = userinfo[@"imageBase64String"];
        if ([imageString rangeOfString:@"data:image/png;base64,"].location != NSNotFound) {
            //如果存在字符串
            imageString = [imageString stringByReplacingOccurrencesOfString:@"data:image/png;base64," withString:@""];
        }
//        UIImage * image = [NSString getImageByBase64String:imageString];
//        if (image) {
//            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
//        }else {
//            [self showHudWithMsg:@"保存失败"];
//        }
    }
}
//保存图片成功调用的方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    
    if (error) {
        // 保存失败
        [self showHudWithMsg:@"保存失败"];
    } else {
        // 保存成功
        [self showHudWithMsg:@"保存成功"];
    }
}

//html中需要统计 调用的通知
- (void)statisticsEventNotification:(NSNotification *)notification
{
    NSDictionary * userInfo = [notification userInfo];
    if (userInfo) {
        if (userInfo[@"eventId"]) {
            if (userInfo[@"questionId"]) {
                //如果存在问题id，则为统计问题
//                [self statisticsEventWithEventID:userInfo[@"eventId"] parameters:@{@"questionId":userInfo[@"questionId"]}];
            }else {
                //如果不存在问题id，则为统计 当面邀请
//                [self statisticsEventWithEventID:userInfo[@"eventId"]];
            }
        }
    }
}


//MARK: ----- UIWebView delegate -----

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//    NSLog(@"允许通过");
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
//    NSLog(@"开始加载");
}

-(void)webViewDidFinishLoad:(UIWebView *)webView
{
//    NSLog(@"完成加载");
    if (self.mainWebView.hidden == YES) {
        self.mainWebView.hidden = NO;
    }
//    if (self.reloadBtn.hidden == NO) {
//        self.reloadBtn.hidden = YES;
//    }
    
    //加载完成，设置nav标题
    self.baseNavView.navTitleLabel.text = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];

    
    //js调用app方法，需要的写法
    JSContext * context = [self.mainWebView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    XXTGHomeWebObject * object = [XXTGHomeWebObject new];
    //创建中转对象，赋值给js的对象
    context[@"jsUseAppMethod"] = object;
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
//    NSLog(@"加载失败");
    if (self.mainWebView.hidden == NO) {
        self.mainWebView.hidden = YES;
    }
//    if (self.reloadBtn.hidden == YES) {
//        self.reloadBtn.hidden = NO;
//    }
}



//WKNavigationDelegate
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//    //    NSLog(@"是否允许这个导航");
//    if ([kUserDefaults objectForKey:kUserCookie]) {
//        NSString * cookie;
//        NSString * sid = @"";
//        if ([kUserDefaults valueForKey:kUserSid]) {
//            NSArray * sidArray = [kUserDefaults valueForKey:kUserSid];
//            if (sidArray && sidArray.count > 0) {
//                sid = [sidArray firstObject];
//                cookie = [NSString stringWithFormat:@"%@=%@;%@=%@",kWebViewCookieKey,[kUserDefaults objectForKey:kUserCookie],kWebViewCookieSidKey,sid];
//            }else{
//                cookie = [NSString stringWithFormat:@"%@=%@",kWebViewCookieKey,[kUserDefaults objectForKey:kUserCookie]];
//            }
//        }else{
//            cookie = [NSString stringWithFormat:@"%@=%@",kWebViewCookieKey,[kUserDefaults objectForKey:kUserCookie]];
//        }
//
//        if ([navigationAction.request allHTTPHeaderFields][@"Cookie"] && [[navigationAction.request allHTTPHeaderFields][@"Cookie"] rangeOfString:cookie].length > 0) {
//            decisionHandler(WKNavigationActionPolicyAllow);
//        } else {
//            NSMutableURLRequest *request= [NSMutableURLRequest requestWithURL:navigationAction.request.URL];
//            [request setValue:cookie forHTTPHeaderField:@"Cookie"];
//            [webView loadRequest:request];
//            decisionHandler(WKNavigationActionPolicyCancel);
//        }
//    }else{
//        decisionHandler(WKNavigationActionPolicyAllow);
//    }
//}
//
//- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
//    //    Decides whether to allow or cancel a navigation after its response is known.
//
//    //    NSLog(@"知道返回内容之后，是否允许加载，允许加载");
//    decisionHandler(WKNavigationResponsePolicyAllow);
//}
//
//- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
//    //    NSLog(@"开始加载");
//    //    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
//
//}
//
//- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
//    NSLog(@"跳转到其他的服务器");
//
//}
//
//- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
//    NSLog(@"网页由于某些原因加载失败");
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//}
//
//- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
//    NSLog(@"网页开始接收网页内容");
//}
//
//- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
//    NSLog(@"网页导航加载完毕");
//    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
//
//    self.title = webView.title;
//    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable ss, NSError * _Nullable error) {
//        NSLog(@"----document.title:%@---webView title:%@",ss,webView.title);
//    }];
//}
//
//- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
//    NSLog(@"加载失败,失败原因:%@",[error description]);
//}
//
//- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
//    NSLog(@"网页加载内容进程终止");
//}


@end
